package org.lemon.cla.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lemon.cla.pojo.News;
import org.lemon.cla.mapper.NewsMapper;
import org.lemon.cla.service.INewsService;
import org.lemon.cla.vo.NewsVo;
import org.lemon.cla.dto.request.NewsSearchRequest;
import org.springframework.stereotype.Service;

@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {

    // 辅助方法：处理 NewsVo 中的发布者信息
    private NewsVo processPublisherInfo(NewsVo newsVo) {
        if (newsVo == null) {
            return null;
        }
        // 如果 publisherId 为 null (ON DELETE SET NULL 发生)，或者 publisherIsDeleted 为 true
        if (newsVo.getPublisherId() == null || newsVo.getPublisherIsDeleted() != null && newsVo.getPublisherIsDeleted()) {
            newsVo.setPublisherUsername("未知用户");
            newsVo.setPublisherAvatarUrl(null);
            newsVo.setPublisherRealName("未知");
            newsVo.setPublisherPhone(null);
            newsVo.setPublisherEmail(null);
            newsVo.setPublisherRole(null); // 或者设置为一个默认的未知角色枚举
        }
        return newsVo;
    }

    // 辅助方法：处理分页结果中的发布者信息
    private IPage<NewsVo> processPublisherInfoForPage(IPage<NewsVo> page) {
        if (page != null && page.getRecords() != null) {
            page.getRecords().forEach(this::processPublisherInfo);
        }
        return page;
    }


    @Override
    public NewsVo getNewsVoById(Long newsId) {
        NewsVo newsVo = baseMapper.selectNewsVoById(newsId);
        return processPublisherInfo(newsVo); // 处理单个 NewsVo
    }

    @Override
    public IPage<NewsVo> getAllNewsVo(Page<NewsVo> page) {
        IPage<NewsVo> newsPage = baseMapper.selectNewsVoPage(page);
        return processPublisherInfoForPage(newsPage); // 处理分页结果
    }

    @Override
    public IPage<NewsVo> searchNewsByConditions(Page<NewsVo> page, NewsSearchRequest request) {
        // 如果搜索请求中包含了 publisherName 关键词，我们仍然使用联表查询
        // 否则，如果只按类别查询，我们仍然需要获取 publisher 信息
        IPage<NewsVo> resultPage = baseMapper.selectNewsVoByMultiConditions(page, request);
        return processPublisherInfoForPage(resultPage); // 处理分页结果
    }
}